import nunjucks from 'nunjucks';
import fs from 'fs';

import { ConverterResultModel, ConverterOptions } from './types';
import { getAbsolutelyPath } from '../utils/path.utils';

function configure() {
    nunjucks.configure({ autoescape: false });
}

class MetaToCSSConverter {
    constructor() {
        configure();
    }

    public convert(metaData: ConverterResultModel, options?: ConverterOptions):Promise<Buffer> {
        return new Promise<Buffer>((resolve, reject) => {
            if (!metaData) {
                resolve(undefined);
            }

            const templatePath = getAbsolutelyPath(options?.cssFileOption?.templatePath);

            fs.readFile(templatePath, (err, templateContent: Buffer) => {
                if (!!err) {
                    reject(err);
                }

                resolve(Buffer.from(nunjucks.renderString(String(templateContent), options)));
            });
        });
    }
}

const DefaultMetaToCSSConverter = new MetaToCSSConverter();

export { MetaToCSSConverter, DefaultMetaToCSSConverter };
